package com.cangsan.erhai.security;

import com.cangsan.erhai.common.CheckResult;
import com.cangsan.erhai.entity.SysUser;
import com.cangsan.erhai.service.SysUserService;
import com.cangsan.erhai.service.impl.MyUserServiceDetailsImpl;
import com.cangsan.erhai.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    SysUserService userService;

    @Autowired
    MyUserServiceDetailsImpl myUserServiceDetails;


    private static final List<String> urls = new ArrayList<>(Arrays.asList( "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**"));



    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();
        if(Objects.isNull(token) ||  urls.contains(requestURI)){
            chain.doFilter(request,response);
            return;
        }
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if(!checkResult.isSuccess()){
            switch (checkResult.getErrCode()){
                case JwtConstant.JWT_ERRCODE_NULL:throw new JwtException("token不存在");
                case JwtConstant.JWT_ERRCODE_FAIL:throw new JwtException("token验证不通过");
                case JwtConstant.JWT_ERRCODE_EXPIRE:throw new JwtException("token过期");

            }
        }

        Claims claims = JwtUtils.parseJWT(token);
        String subject = claims.getSubject();
        SysUser sysUser = userService.getByUserName(subject);
        UsernamePasswordAuthenticationToken
                upat = new UsernamePasswordAuthenticationToken(
                sysUser.getUserName(),
               null,
                myUserServiceDetails.getUserAutharity(sysUser.getUserId()));
        SecurityContextHolder.getContext().setAuthentication(upat);
        chain.doFilter(request,response);
    }
}
